package com.hera.process.config.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hera.base.util.FiltroDTO;
import com.hera.process.config.dao.DynaformFieldDao;
import com.hera.process.config.dao.FormFieldDao;
import com.hera.process.config.service.FormFieldService;
import com.hera.process.form.domain.Dynaform;
import com.hera.process.form.domain.FormField;

@Service("formfieldservice")
public class FormFieldServiceImpl implements FormFieldService{

	static final Logger logger = Logger.getLogger(UserServiceImpl.class);
	
	@Autowired
	private FormFieldDao formfielddao;
	
	@Autowired
	private DynaformFieldDao dynaformfielddao;
	
	@Override
	public FormField findById(Long id) {
		
		return formfielddao.findOne(id);
	}

	@Override
	public void update(FormField entity) {
		if(entity.getName() == null || entity.getName().trim() == ""){
			entity.setName("COMPONENT" + entity.getIdField());			
		}
		if(entity.getLabel() == null || entity.getLabel().trim() == ""){
			entity.setLabel(entity.getName());			
		}
		formfielddao.save(entity);
	}

	@Override
	public void save(FormField entity) {
		
		formfielddao.save(entity);
		
		if(entity.getName() == null || entity.getName().trim() == ""){
			entity.setName("COMPONENT" + entity.getIdField());
			entity.setLabel(entity.getName());
			formfielddao.save(entity);
		}
		
		
	}

	@Override
	public void delete(FormField entity) {
		
//		dynaformfielddao.deleteByFormField(entity.get);
		formfielddao.delete(entity);
	}

	@Override
	public List<FormField> findAll() {
		
		return formfielddao.findAll();
	}

	@Override
	public List<FormField> findAll(FiltroDTO filtroDTO) {
		
		return formfielddao.obtenerEntidadesPorFiltros(filtroDTO);
	}
	@Override
	public List<FormField> findByDynaForm(Long idDynaform) {
		// TODO Auto-generated method stub
		return formfielddao.findByDynaForm(idDynaform);
	}

	@Override
	public List<FormField> findAllFormNoasignado(Dynaform dynaform) {
		
		List codigos= dynaformfielddao.findAllFormSiasignadoIds(dynaform.getIdDynaform(),dynaform.getIdProcess());
		if (codigos.size()==0) {
			FiltroDTO filtroDTO= new FiltroDTO();
			filtroDTO.addParametro("idDynaform", dynaform.getIdDynaform());
			filtroDTO.addParametro("idProcess", dynaform.getIdProcess());
			
			return formfielddao.obtenerEntidadesPorFiltros(filtroDTO);
		}else{
			return dynaformfielddao.findAllFormNoasignado(dynaform.getIdProcess(), codigos);
		}
		
		
	}
	
	@Override
	public List<FormField> findByIdProcess(Long idProcess) {
		return formfielddao.findByIdProcess(idProcess);
		
	}

	@Override
	public List<FormField> findFormFieldNoAsignado(Long idDynaform,
			Long idProcess) {
		return formfielddao.findFormFieldNoAsignado(idDynaform, idProcess);
	}

}
